
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from '@src/store/base'
import mall from '@src/store/mall'
import storeClassify from '@src/store/dianpufenlei'
import { getStoreMenu, getStoreGoodsList, getDispatchWay, getStoreDetail } from '@src/api/mall/store'
import { addGoodsToCart, getCartGoods, updateCartGoods, batchDeleteItem } from '@src/api/mall/storeCart'
import { preOrderFun } from '@src/api/mall/order'
import router from "@src/router";
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["homePage"]
    },
    {
      store: mall,
      fields: ['curLocation', 'storeId']
    },
    {
      store: storeClassify,
      fields: [
        'menuData', 
        'goodsData', 
        'selectedMenuId', 
        'twoMenu',
        'menuSelectedIndex',
        'twoMenuSelectedIndex',
        'hasDianpujianjie',
        'cartList',
        'items',
        'priceCount',
        'cartIds',
        'cartNum',
        'storeAboutHeight',
        'top'
      ],
      actions: [
        'getStoreGoodsList', 
        'setSelectedMenuId', 
        'getFetchData',
        'getCartGoods'
      ]
    }
  ],
  properties: {
    top: {
      type: Boolean,
      value: false
    },
    isShow: {
      type: Boolean
    },
    login: {
      type: Boolean
    }
  },
  data: {
    dispatchShow: false,
    skuShow: false,
    twoClassifyShow: false,
    fileBaseUrl: null,
    // 当前选中商品
    goodsSelected: {},
    // skuId
    skuSelectedIds: [],
    // 筛选出来的sku
    selectedSkuData: {},
    cartAddForm: {
      cartType: 0,
      children: [],
      goodsId: null,
      num: 1,
      remark: null,
      skuId: null,
      storeId: null,
      type: 'NO_CHOICE'
    },
    lock: false,
    // cartList: [],
    // items: [],
    // priceCount: 0,
    // cartIds: [],
    deliveryType: null,
    source: 0,
    nowBuyItem: [],
    storeInfo: {},
    isOpenDispatch: true,
    // cartNum: 0,
    scrollTop: 0,
    statusbarHeight: 80,
    isPreviewImage: false,
    dispatchWayDescribe: [
      {
        title: '外卖配送',
        describe: '支持配送',
        image: '../../../static/icon/take_out.png',
        status: 2,
        str: 'LOCAL',
        disabled: false,
        isShow: false,
        goods: []
      },
      {
        title: '到店自提',
        describe: '支持自提',
        image: '../../../static/icon/store.png',
        status: 2,
        str: 'SELF_PICKUP',
        disabled: false,
        isShow: false,
        goods: []
      },
      {
        title: '快递邮寄',
        describe: '支持邮寄',
        image: '../../../static/icon/fast_mail.png',
        status: 2,
        str: 'EXPRESS',
        disabled: false,
        isShow: false,
        goods: []
      }
    ]
  },
  observers: {
    // pageScrollTop(pageScrollTop) {
    //   const { storeAboutQuery } = getApp().globalData
    //   if (!storeAboutQuery) return
    //   storeAboutQuery.then(query => {
    //     query.exec((res) => {
    //       this.setData({ top: (pageScrollTop >= res[0].height) })
    //     })
    //   })
    // },
    top(top) {
      wx.setPageStyle({
        style: {
          background: (top ? '#fff' : '#f7f7f7')
        }
      })
    },
    isShow(isShow) {
      if(this.data.isPreviewImage) {
        this.setData({isPreviewImage: false})
        return
      }
      if (!isShow || !this.data.storeId) return
      this.setData({
        menuSelectedIndex: 0,
        twoMenuSelectedIndex: 0
      })
      this.getFetchData(this.data.homePage)
      if(!this.data.login) return
      this.getCartGoods()
    },
    storeId(storeId) {
      if(!this.data.homePage || !storeId) return
      this.getFetchData(this.data.homePage)
      this.setData({
        menuSelectedIndex: 0,
        twoMenuSelectedIndex: 0
      })
      if(!this.data.login) return
      this.getCartGoods()
    },
    selectedMenuId(selectedMenuId) {
      if (!this.data.storeId || !selectedMenuId) return
      this.getStoreGoodsList(selectedMenuId)
      this.getStoreInfo()
    },
    homePage(homePage) {
      if (!homePage.modules) return
      this.setData({
        menuSelectedIndex: 0,
        twoMenuSelectedIndex: 0
      })
      this.getFetchData(homePage)
    }
  },
  lifetimes: {
    ready() {
      const systemInfo = wx.getSystemInfoSync();
      const fileBaseUrl = getApp().globalData.extConfig.fileBaseUrl
      this.setData({ fileBaseUrl, statusbarHeight: systemInfo.statusBarHeight })
      wx.setPageStyle({
        style: {
          background: (!this.data.hasDianpujianjie ? '#fff' : '#f7f7f7')
        }
      })
      if(!this.data.login) return
      this.getCartGoods()
    }
  },
  methods: {
    getStoreInfo() {
      getStoreDetail({ storeId: this.data.storeId })
        .then(res => {
          const { supplyLocal, supplySelfPickup, supplyExpress } = res.data.delivery
          if (!supplyLocal && !supplySelfPickup && !supplyExpress) {
            this.setData({ isOpenDispatch: false, storeInfo: res.data })
            return
          }

          let dispatchWayDescribe = this.data.dispatchWayDescribe
          dispatchWayDescribe[0].isShow = false
          dispatchWayDescribe[1].isShow = false
          dispatchWayDescribe[2].isShow = false
          supplyLocal && (dispatchWayDescribe[0].isShow = true)
          supplySelfPickup && (dispatchWayDescribe[1].isShow = true)
          supplyExpress && (dispatchWayDescribe[2].isShow = true)
          this.setData({ dispatchWayDescribe, storeInfo: res.data })
        })
    },
    toCart() {
      if (!this.data.login) {
        this.triggerEvent('login');
        return
      }
      router.push({
        name: 'mall/store-cart'
      })

    },
    previewImage({ currentTarget }) {
      
      const { urls } = currentTarget.dataset
      let images = []
      urls.forEach(item => { images.push(this.data.fileBaseUrl + item) })
      wx.previewImage({
        urls: images,
        success:() => {
          this.setData({isPreviewImage: true})
        }
      })
    },
    dispatchHide() {
      this.setData({ dispatchShow: false })
    },
    placeOrder({ currentTarget }) {
      const { str: type, source = 0 } = currentTarget.dataset
      const { items: items, storeId } = this.data

      const params = {
        items,
        type,
        source,
        storeId
      }

      preOrderFun(params).then(res => {
        if (res.code === 0) {
          router.push({ name: 'mall/submit-order-virtual', params: { preNo: res.data.preNo } })
        } else {
          wx.showToast({
            title: '购买失败，晚点试试把',
            icon: 'none',
            duration: 3000
          })
        }
      })

    },
    getDispatchWay() {
      if (!this.data.login) {
        this.triggerEvent('login');
        return
      }
      const { supplyExpress, supplyLocal, supplySelfPickup } = this.data.storeInfo.delivery
      const { source, items } = this.data
      if (!supplyExpress && !supplyLocal && !supplySelfPickup) {
        wx.showToast({
          title: '当前门店未配置任何配送方式，暂时无法下单',
          icon: 'none'
        })
        return
      }
      if (source === 0 && !items.length) return
      console.log(this.data.cartList)
      let params = {
        items: (this.data.source == 0 ? this.data.items : this.data.nowBuyItem),
        storeId: this.data.storeId,
        subType: '',
        source: this.data.source
      }

      getDispatchWay(params)
        .then(res => {
          if (res.code !== 0) return
          this.setData({ dispatchShow: true })
          let dispatchWayDescribe = this.data.dispatchWayDescribe
          const {
            supplyExpress,
            expressItems,
            localItems,
            selfPickupItems,
            supplyLocal,
            supplySelfPickup
          } = res.data
          dispatchWayDescribe[0].disabled = !!!supplyLocal
          dispatchWayDescribe[0].status = supplyLocal
          dispatchWayDescribe[0].goods = localItems
          dispatchWayDescribe[1].disabled = !!!supplySelfPickup
          dispatchWayDescribe[1].status = supplySelfPickup
          dispatchWayDescribe[1].goods = selfPickupItems
          dispatchWayDescribe[2].disabled = !!!supplyExpress
          dispatchWayDescribe[2].status = supplyExpress
          dispatchWayDescribe[2].goods = expressItems
          this.setData({ dispatchWayDescribe })
        })
        .catch(err => {
          this.setData({ source: 0, skuShow: false, nowBuyItem: [] })
        })

    },
    selectedDispatchWay({ currentTarget }) {
      const { dispatch } = currentTarget.dataset
      if (dispatch.disabled) return
      this.setData({ deliveryType: dispatch.str })
      this.handlePreOrder(dispatch.goods)
    },
    buyNow() {
      const { status } = this.data.storeInfo
      if (status !== 1) {
        wx.showToast({
          title: '门店已打烊',
          icon: 'none'
        })
        return
      }
      if (this.data.selectedSkuData.stockNum <= 0) {
        wx.showToast({
          title: '已售罄',
          icon: 'none'
        })
        return
      }
      let item = {
        goodsId: this.data.goodsSelected.goodId,
        num: this.data.cartAddForm.num,
        price: this.data.selectedSkuData.price,
        skuId: this.data.selectedSkuData.skuId,
        storeId: this.data.storeId
      }
      this.setData({ source: 1, skuShow: false, nowBuyItem: [item] })
      this.getDispatchWay()
    },
    handlePreOrder(goods = []) {
      let selectCartList = (this.data.source == 0 ? goods : this.data.nowBuyItem)
      if (selectCartList.length === 0) {
        return;
      }

      let orderPreForm = {
        items: [],
        source: this.data.source,
        storeId: this.data.storeId,
        type: this.data.deliveryType,
        subType: ""
      };
      console.info()
      selectCartList.forEach(item => {
        orderPreForm.items.push(item)
      })
      wx.showLoading({ title: "下单中...", mark: true });
      let deliveryType = this.data.deliveryType
      preOrderFun(orderPreForm).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          this.setData({ dispatchShow: false, source: 0 })
          router.push({
            name: 'mall/submit-order',
            params: {
              preNo: res.data.preNo,
              deliveryType: deliveryType,
              storeNo: this.data.storeInfo.storeNo
            },
            success: (res) => {
              if (deliveryType === 'LOCAL') {
                setTimeout(() => {
                  res.eventChannel.emit('showSelectDelivery');
                }, 300)
              }
            }
          })
        }
      }).catch((res) => {
        this.setData({ dispatchShow: false, source: 0 })
        if (res.data.data.invalidItems.length > 0) {
          wx.showToast({
            icon: 'none',
            title: res.data.data.invalidItems[0].title + res.data.data.invalidItems[0].errorMsg,
          })
        }
      })
    },
    async addBtn(e) {
      const { goodinfo, isadd, count } = e.currentTarget.dataset
      const { skuInfo } = goodinfo
      const { items } = this.data
      if (!this.data.login) {
        this.triggerEvent('login');
        return
      }
      if (skuInfo.skuList.length <= 1 && skuInfo.skuList[0].stockNum <= 0) {
        wx.showToast({
          title: '已售罄',
          icon: 'none'
        })
        return
      }
      //有多sku
      if (skuInfo.skuList.length > 1) {
        const filterGoods = items.filter(item => goodinfo.goodId === item.goodsId)
        if (!isadd && filterGoods.length <= 1 && filterGoods[0].num > 1) {
          let { cartItemId, storeId, num, goodsId, skuId } = filterGoods[0]
          let params = {
            cartItemId,
            storeId,
            num: --num,
            goodsId,
            skuId
          }
          await updateCartGoods(params)
          this.getCartGoods()

          return
        } else if (!isadd && filterGoods.length > 1) {
          wx.showToast({
            title: '请到购物车减购',
            icon: 'none'
          })
          return
        } else if (!isadd && filterGoods.length <= 1 && filterGoods[0].num <= 1) {
          let { cartItemId, storeId } = filterGoods[0]
          batchDeleteItem([{ cartItemId, storeId }]).then(res => {
            this.getCartGoods()
          })
          return
        }


        this.openSku(e)
        return
      }
      this.setData({ goodsSelected: goodinfo, selectedSkuData: goodinfo.skuInfo.skuList[0] })
      //单个sku
      if (isadd) {
        this.addCart()
      } else if (!isadd && count > 1) {
        const filter = this.data.items.filter(item => item.goodsId === goodinfo.goodId)[0]
        let { cartItemId, storeId, num, goodsId, skuId } = filter
        let params = {
          cartItemId,
          storeId,
          num: --num,
          goodsId,
          skuId
        }
        await updateCartGoods(params)
        this.getCartGoods()
      } else if (!isadd && count <= 1) {
        const filter = this.data.items.filter(item => item.goodsId === goodinfo.goodId)[0]
        let { cartItemId, storeId } = filter
        batchDeleteItem([{ cartItemId, storeId }]).then(res => {
          this.getCartGoods()
        })
      }
    },
    //初始化购物车函数
    initCartChange() {
      const cartAddForm = {
        cartType: 0,
        children: [],
        goodsId: null,
        num: 1,
        remark: null,
        skuId: null,
        storeId: null,
        type: 'NO_CHOICE'
      }
      this.setData({
        cartAddForm,
        skuShow: false
      })
      this.getCartGoods()
    },
    // getCartGoods() {
    //   if (!this.data.login) return
    //   getCartGoods({ cartType: 0, storeId: this.data.storeId, type: 'NO_CHOICE' })
    //     .then(res => {
    //       this.setData({ cartList: res.data })
    //       let cartList = []
    //       let menuData = this.data.menuData
    //       menuData.forEach(item => { item.count = 0 })
    //       let map = res.data.map(item => item.items)
    //       map.forEach(item => { cartList.push(...item) })
    //       let priceCount = cartList.reduce((prev, cur) => prev + (cur.price * cur.num), 0)
    //       const cartIds = cartList.map(item => item.goodsId)
    //       let cartNum = 0;
    //       cartList.forEach(item => {
    //         cartNum += item.num
    //         menuData.forEach(mItem => {
    //           if (item.menuIdList.includes(mItem.menuId)) {
    //             mItem.count += item.num
    //           }

    //         })
    //       })
    //       this.setData({ items: cartList, priceCount, cartIds, menuData, cartNum })
    //     })
    // },
    //添加购物车
    addCart() {
      const { goodId } = this.data.goodsSelected
      const cartAddForm = this.data.cartAddForm
      cartAddForm.storeId = this.data.storeId
      cartAddForm.goodsId = goodId
      cartAddForm.skuId = this.data.selectedSkuData.skuId
      if (this.data.selectedSkuData.stockNum === 0) {
        wx.showToast({
          title: '已售罄',
          icon: 'none',
          duration: 1000
        })
        return
      }
      addGoodsToCart(cartAddForm)
        .then(res => {
          wx.showToast({
            title: '宝贝已添加到购物车',
            icon: 'none',
            duration: 1000
          })
          this.initCartChange()
        })

    },
    // 计算count
    countChange({ currentTarget }) {
      const { isadd } = currentTarget.dataset
      const { num } = this.data.cartAddForm
      const cartAddForm = this.data.cartAddForm
      const stockNum = this.data.selectedSkuData.stockNum
      if (isadd && num >= stockNum) {
        wx.showToast({
          title: '商品库存不足',
          icon: 'none',
          duration: 1000
        })
        return
      }
      if (isadd && num < stockNum) {
        cartAddForm.num += 1
      } else if (!isadd && num > 1) {
        cartAddForm.num -= 1
      }
      this.setData({ cartAddForm })
    },
    //选择分类
    selectedMenu({ currentTarget }) {
      const { index, data } = currentTarget.dataset
      const { type, goodsMenuForms, menuId } = data
      if (!this.data.login) {
        this.triggerEvent('login');
        return
      }
      if (index === this.data.menuSelectedIndex) return
      if(this.data.hasDianpujianjie && this.data.top) {
        wx.pageScrollTo({
          scrollTop: (this.data.storeAboutHeight + 1)
        })
      } else if(!this.data.hasDianpujianjie) {
        wx.pageScrollTo({
          scrollTop: 0
        })
      }
      
      this.setData({
        twoMenuSelectedIndex: 0,
        menuSelectedIndex: index,
        twoMenu: type === 2 ? goodsMenuForms : [],
        twoClassifyShow: false
      })
      const selectedMenuId = type !== 2 ? menuId : goodsMenuForms[0].menuId
      this.setSelectedMenuId(selectedMenuId)
    },
    //选择二级分类
    twoSelectedMenu({ currentTarget }) {
      const { index, menuid } = currentTarget.dataset
      if (index === this.data.twoMenuSelectedIndex) return
      if(this.data.hasDianpujianjie && this.data.top) {
        wx.pageScrollTo({
          scrollTop: (this.data.storeAboutHeight + 1)
        })
      } else if(!this.data.hasDianpujianjie) {
        wx.pageScrollTo({
          scrollTop: 0
        })
      }
      this.setData({
        twoMenuSelectedIndex: index,
      })
      this.setSelectedMenuId(menuid)
    },
    //获取分类
    // getStoreMenuFetchData(menuIdList) {
    //   if (!menuIdList || !menuIdList.length) return
    //   getStoreMenu(menuIdList)
    //     .then(res => {
    //       const { data } = res
    //       const { type, menuId, goodsMenuForms } = data[this.data.menuSelectedIndex]
    //       this.setData({ menuData: data, twoMenu: type === 2 ? goodsMenuForms : [] })
    //       if (type !== 2) {
    //         this.getStoreGoodsList(menuId)
    //       } else {
    //         this.getStoreGoodsList(goodsMenuForms[0].menuId)
    //       }
    //     })
    // },
    // getStoreGoodsList(menuId) {
    //   if (this.data.lock) return
    //   getStoreGoodsList(this.data.storeId, { menuId, pageNum: this.data.pageNum, pageSize: 10 })
    //     .then(res => {
    //       const { data } = res
    //       if (data.list.length >= 10) {
    //         this.setData({ pageNum: ++this.data.pageNum })
    //       } else {
    //         this.setData({ lock: true })
    //       }
    //       const goodsData = [...this.data.goodsData, ...data.list]
    //       this.setData({ goodsData })
    //     })
    // },

    openSku({ currentTarget }) {
      if (!this.data.login) {
        this.triggerEvent('login');
        return
      }
      const { goodinfo } = currentTarget.dataset
      const { skuList, specList } = goodinfo.skuInfo
      this.setData({ skuShow: true, goodsSelected: goodinfo })
      //打开窗口自动选择第一个sku

      if (!this.data.skuSelectedIds.length) {
        let skuSelectedIds = skuList[0].specAttrs.slice(0, specList.length)
        this.setData({ skuSelectedIds, selectedSkuData: skuList[0] })
      }

    },
    isShowTwoClassify() {
      this.setData({ twoClassifyShow: !this.data.twoClassifyShow })
    },
    popSkuChange({ currentTarget }) {
      const { index, id } = currentTarget.dataset
      const { skuList, specList } = this.data.goodsSelected.skuInfo
      const cartAddForm = this.data.cartAddForm
      const ids = this.data.skuSelectedIds
      ids[index] = id
      this.setData({ skuSelectedIds: ids })
      let selectedSkuData = skuList.filter((item) => {
        let specAttr = item.specAttrs.slice(0, specList.length)
        return JSON.stringify(specAttr) === JSON.stringify(ids)
      })?.[0]

      if (!selectedSkuData) {
        return
      }
      if (selectedSkuData.stockNum == 0) {
        cartAddForm.num = 1
      }
      if (cartAddForm.num > selectedSkuData.stockNum && selectedSkuData.stockNum !== 0) {
        cartAddForm.num = selectedSkuData.stockNum
      }


      this.setData({ selectedSkuData, cartAddForm })
    },
  }
})
